package com.cangheng.app.util.socketTest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class ServerThread implements Runnable{

	// 定义当前线所处理的Socket
	private Socket s = null;
	// 对应线程所处理的 Socket对应的输入流
	private BufferedReader br = null;
	public ServerThread (Socket s) throws IOException {
		this.s = s;
		// 初始化改 Socket对应的输入流
		br = new BufferedReader(new InputStreamReader(s.getInputStream()));
	}
	@Override
	public void run() {
		try {
			String content = null;
			// 采用循环不断地从 Socket中读取客户端发送过来的数据
			while ((content = readFromClient()) != null) {
				// 遍历 socketList中每个socket
				// 将读到的内容向每个Socket发送一次
				for (Socket s : Server.socketList) {
					PrintStream ps = new PrintStream(s.getOutputStream());
					ps.println(content);
				}
			}
			System.out.println("close");
		} catch (Exception e) {
			
		}
	}

	// 定义读取客户端数据的方法
	private String readFromClient () {
		try {
			return br.readLine();
		}
		// 如果捕获到异常，则表明该 Socket对应的客户端已经关闭
		catch (IOException e) {
			Server.socketList.remove(s);
		}
		return null;
	}
}